import XGPlayer from 'xgplayer'
import FlvPlayer from 'xgplayer-flv'
import HlsPlayer from 'xgplayer-hls'
import { EventEmitter } from 'events'
import './skin/index.js'

export class VideoPlayer extends EventEmitter {

  constructor(options) {

    super()

    this.shotImg = '';
    if (options.url) {
      this.type = options.url.split('.').pop() || 'mp4'

      if (this.type.indexOf('flv') !== -1) {
        this.player = new FlvPlayer(options)
      } else {
        if (this.type.indexOf('m3u8') !== -1) {
          this.player = new HlsPlayer(options)
        } else {
          this.player = new XGPlayer(options)
        }
      }
      this.bindEvents()
    }
    
  }

  bindEvents() {
    this.player.once('ready', () => {
      this.emit('phaseChanged', (this.phaseState = 'init'))
    })

    this.player.on('play', () => {
      this.emit('phaseChanged', (this.phaseState = 'playing'))
    })

    this.player.on('pause', () => {
      this.emit('phaseChanged', (this.phaseState = 'paused'))
    })

    this.player.once('ended', () => {
      this.emit('phaseChanged', (this.phaseState = 'ended'))
    })

    this.player.on('error', () => {
      console.error('error', this.phaseState)
    })

    this.player.on('screenShot', (val) => { // 截图数据base64
        this.shotImg = val;
    })
  }

  getIsPlaying() {
    return !this.player.paused
  }

  getShotImg() {
    //  let blobUrl = dataURLtoBlob(this.shotImg);
     return dataURLToFile(this.shotImg, '截图.png');
  }

  play() {
    if (!this.getIsPlaying()) {
        this.player.play()
    }
  }

  pause() {
    if (this.getIsPlaying()) {
      this.player.pause()
    }
  }

  destroy() {
     this.player.destroy()
  }

  screenCustomShot() {
      this.player.emit('screenShotBtnClick');
  }

}


// function dataURLtoBlob (dataurl) {
//     let arr = dataurl.split(','),
//     mime = arr[0].match(/:(.*?);/)[1],
//     bstr = window.atob(arr[1]),
//     n = bstr.length,
//     u8arr = new Uint8Array(n);
//     while (n--) {
//         u8arr[n] = bstr.charCodeAt(n);
//     }
//     return new Blob([u8arr], { type: mime });
// }


function dataURLToFile(dataURL, filename){
    const arr = dataURL.split(','),
        mime = arr[0].match(/:(.*?);/)[1], //mime类型 image/png
        bstr = window.atob(arr[1]); //base64 解码
        
    let n = bstr.length,
        u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    
    return new File([u8arr], filename, {type: mime});
}


function blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

export default VideoPlayer
